package com.yindian.cos.easy.security.authentication.token;

import com.yindian.cos.easy.security.exception.AccessTokenIllegalException;
import com.yindian.cos.easy.security.properties.TokenProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * token默认存储策略（redis）
 *
 * @author zhangchuanhao
 * @create 2018/11/21
 */
@Log4j2
public class RedisTokenStore extends TokenStore {

    private RedisTemplate<String, Token> redisTemplate;

    private TokenProperties tokenProperties;

    public RedisTokenStore(RedisTemplate redisTemplate, TokenProperties tokenProperties) {
        this.redisTemplate = redisTemplate;
        this.tokenProperties = tokenProperties;
    }

    /**
     * 根据token解析获取token key
     *
     * @param token
     * @return
     */
    public String getTokenKeyByToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(tokenProperties.getJwtSecretKey())
                    .parseClaimsJws(token)
                    .getBody();
            String tokenKey = (String) claims.get(JwtTokenFactory.TOKEN_KEY);
            if (StringUtils.isBlank(tokenKey)) {
                throw new AccessTokenIllegalException("非法的token， " + token);
            }
            return tokenKey;
        } catch (Exception e) {
            throw new AccessTokenIllegalException("非法的token，token: " + token);
        }
    }

    @Override
    public boolean saveToken(Token token) {
        // 设置用户token绑定关系,K：登录过滤器类名 + userId，V：token
        set(token.getTokenKey(), token, token.getRefreshTokenExpire());
        return true;
    }

    @Override
    public boolean removeToken(String accessToken) {
        Token token = getTokenByAccessToken(accessToken);
        if (token == null || !token.getAccessToken().equals(accessToken)) {
            throw new AccessTokenIllegalException("非法的token，token: " + accessToken);
        }
        return del(token.getTokenKey());
    }

    @Override
    public Token getTokenByAccessToken(String accessToken) {
        String tokenKey = getTokenKeyByToken(accessToken);
        return getToken(tokenKey);
    }

    @Override
    public Token getTokenByRefreshToken(String refreshToken) {
        return getTokenByAccessToken(refreshToken);
    }

    @Override
    public Token getTokenByUserId(String userId) {
        return getToken(userId);
    }

    @Override
    public boolean isAccessTokenNonExpired(Token token) {
        if (token == null) {
            return true;
        }
        // 计算token已使用时间
        long time = System.currentTimeMillis() - token.getCreateTime().getTime();
        // 计算accessToken的过期时间
        long accessTokenExpire = token.getAccessTokenExpire() * 1000;
        // 计算accessToken是否过期
        return accessTokenExpire - time < 0;
    }

    /**
     * 存储token
     *
     * @param k
     * @param token
     * @param expire
     * @return
     */
    private boolean set(String k, Token token, int expire) {
        redisTemplate.opsForValue().set(k, token, expire, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 删除key
     *
     * @param key
     * @return
     */
    private boolean del(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 根据key获取token
     *
     * @param key accessToken或者refreshToken
     * @return
     */
    private Token getToken(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}
